#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Base{
public:
    Base(const char * pbase)
        : _pbase(new char[strlen(pbase) + 1]())
    {
        strcpy(_pbase,pbase);
    }

    Base(const Base & rhs)
        : _pbase(new char[strlen(rhs._pbase) + 1]())
    {
        strcpy(_pbase,rhs._pbase);
    }

    Base & operator=(const Base & rhs)
    {
        if(this != &rhs){
            delete [] _pbase;
            _pbase = new char[strlen(rhs._pbase) + 1]();
            strcpy(_pbase,rhs._pbase);
        }
        return *this;
    }

    void print() const{
        cout << _pbase << endl;
    }

    ~Base(){
        if(_pbase){
            delete [] _pbase;
            _pbase = nullptr;
        }
    }

protected:
    char * _pbase;
};

class Derived
: public Base
{
public:
    Derived(const char * pbase,const char * pderived)
        : Base(pbase)
          , _pderived(new char[strlen(pderived) + 1]())
    {
        strcpy(_pderived,pderived);
    }

    Derived(const Derived & rhs)
        : Base(rhs)//关键
          , _pderived(new char[strlen(rhs._pderived) + 1]())
    {
        strcpy(_pderived,rhs._pderived);
    }

    Derived & operator=(const Derived & rhs){
        if(this != &rhs){
            //一定要显式调用基类相应的赋值运算符函数
            Base::operator=(rhs);//关键
            delete [] _pderived;
            _pderived = new char[strlen(rhs._pderived) + 1]();
            strcpy(_pderived,rhs._pderived);
        }
        return *this;
    }

    void display() const{
        print();
        cout << _pderived << endl;
        cout << _derived << endl;
    }

    ~Derived(){
        if(_pderived){
            delete [] _pderived;
            _pderived = nullptr;
        }
    }

protected:
    char * _pderived;
    long _derived = 10;
};

void test0(){
    Derived d1("hello","world");
    d1.display();
    cout << "执行拷贝构造：" << endl;
    Derived d2 = d1;
    d2.display();

#if 1
    cout << "赋值运算符函数" << endl;
    Derived d3("yes","100 offer!");
    d2 = d3;
    d2.display();
#endif
}

int main(void){
    test0();
    return 0;
}
